import Component from '../models/component.model.js';

class ComponentController {
 static async getAllComponents(req, res) {
    try {
      const components = await Component.getAll();
      res.status(200).json(components);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }


  static async getComponentById(req, res) {
    try {
      const component = await Component.getById(req.params.id);
      if (!component) {
        return res.status(404).json({ error: 'Component not found' });
      }
      res.status(200).json(component);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }

  static async getComponentByName(req, res) {
    try {
      const { name } = req.params;
      const component = await Component.getByName(name);
      if (!component) {
        return res.status(404).json({ message: '组件不存在' });
      }
      res.status(200).json(component);
    } catch (error) {
      res.status(500).json({ message: '获取组件详情失败', error: error.message });
    }
  }

  static async createComponent(req, res) {
    try {
      const { name, description } = req.body;
      if (!name) {
        return res.status(400).json({ message: '组件名称不能为空' });
      }
      
      const existingComponent = await Component.getByName(name);
      if (existingComponent) {
        return res.status(409).json({ message: '组件名称已存在' });
      }
      
      const componentId = await Component.create(name, description);
      const newComponent = await Component.getById(componentId);
      res.status(201).json(newComponent);
    } catch (error) {
      res.status(500).json({ message: '创建组件失败', error: error.message });
    }
  }

  static async updateComponent(req, res) {
    try {
      const { id } = req.params;
      const updateData = req.body;
      
      const component = await Component.getById(id);
      if (!component) {
        return res.status(404).json({ message: '组件不存在' });
      }
      
      // 检查是否修改了名称且新名称已存在
      if (updateData.name && updateData.name !== component.name) {
        const existingComponent = await Component.getByName(updateData.name);
        if (existingComponent) {
          return res.status(409).json({ message: '组件名称已存在' });
        }
      }
      
      const updatedComponent = await Component.update(id, updateData);
      res.status(200).json(updatedComponent);
    } catch (error) {
      res.status(500).json({ message: '更新组件失败', error: error.message });
    }
  }

  static async deleteComponent(req, res) {
    try {
      const { id } = req.params;
      
      const component = await Component.getById(id);
      if (!component) {
        return res.status(404).json({ message: '组件不存在' });
      }
      
      await Component.delete(id);
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ message: '删除组件失败', error: error.message });
    }
  }
}

export default ComponentController;